import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Message, Modal } from '@arco-design/web-react';
import { updateUserExtralInfo } from '@/api/userData';

const FormItem = Form.Item;

interface Props {
  visible: boolean;
  modalTitle: string;
  editData: object;
  changeVisible: (visible: boolean) => void;
  onConfirm: () => void;
}

function FormModal(props: Props) {
  const { visible, editData, changeVisible, modalTitle, onConfirm } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    form.setFieldsValue(editData);
    setLoading(false);
  }, [visible]);

  const onOk = () => {
    form.validate().then(async (data) => {
      setLoading(true);
      const res: any = await updateUserExtralInfo({
        CTLUserId: (editData as any).CTLUserId, //C端用户Id
        CTLUserName: data.CTLUserName, //用户名
        CTLAccount: data.CTLAccount, //账号名
        Alias: data.Alias, //学生名
      });

      setLoading(false);
      if (res.StatusCode === 200) {
        Message.success(res.Message);
        onConfirm();
        changeVisible(false);
      } else {
        Message.error(res.Message);
      }
    });
  };

  const onCancel = () => {
    if (loading) return;
    form.resetFields();
    changeVisible(false);
  };

  const CTLAccountRules = (value, callback) => {
    if (!value) {
      return callback('请输入校园账号');
    }
    if (!/^[0-9]*$/.test(value)) {
      return callback('请输入数字');
    }

    if (value.length < 3 || value.length > 16) {
      return callback('请输入3-16位的数字');
    }
    return callback();
  };

  return (
    <Modal
      title={modalTitle}
      visible={visible}
      onCancel={onCancel}
      autoFocus={false}
      focusLock={false}
      style={{ width: '700px' }}
      footer={
        <Button type="primary" loading={loading} onClick={onOk}>
          确认
        </Button>
      }
    >
      <Form form={form}>
        <FormItem
          label="校园账号"
          field="CTLAccount"
          rules={[
            {
              required: true,
              validator: CTLAccountRules,
            },
          ]}
        >
          <Input placeholder="请输入" autoComplete="off" />
        </FormItem>
        <FormItem
          label="姓名"
          field="Alias"
          rules={[
            {
              required: true,
              message: '请输入姓名',
            },
          ]}
        >
          <Input placeholder="请输入" autoComplete="off" />
        </FormItem>
        <FormItem
          label="用户昵称"
          field="CTLUserName"
          rules={[
            {
              required: true,
              message: '请输入用户昵称',
            },
          ]}
        >
          <Input placeholder="请输入" autoComplete="off" />
        </FormItem>
      </Form>
    </Modal>
  );
}

export default FormModal;
